package com.situ.blog.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.situ.blog.pojo.User;
import com.situ.blog.pojo.UserLogin;
import com.situ.blog.pojo.query.UserQuery;
import com.situ.blog.service.IUserService;
import com.situ.blog.util.CommonUtil;
import com.situ.blog.util.JwtUtil;
import com.situ.blog.util.Result;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dell
 * @since 2024-09-20
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IUserService userService;

    @GetMapping("/list")
    public Result list(UserQuery userQuery) {
        IPage<User> userIPage = new Page<>(userQuery.getPage(), userQuery.getLimit());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(!ObjectUtils.isEmpty(userQuery.getName()), "name", userQuery.getName());
        queryWrapper.like(!ObjectUtils.isEmpty(userQuery.getPhone()), "phone", userQuery.getPhone());
        queryWrapper.between(!ObjectUtils.isEmpty(userQuery.getBeginCreateTime()) && !ObjectUtils.isEmpty(userQuery.getEndCreateTime()),
                "create_time", userQuery.getBeginCreateTime(), userQuery.getEndCreateTime());
        userService.page(userIPage, queryWrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("total", userIPage.getTotal());
        map.put("list", userIPage.getRecords());
        return Result.ok(map);
    }

    @DeleteMapping("/deleteById/{id}")
    public Result deleteById(@PathVariable Integer id) {
        userService.removeById(id);
        return Result.ok("删除成功");
    }

    @DeleteMapping("/deleteAll/{ids}")
    public Result deleteAll(@PathVariable Integer[] ids) {
        userService.removeByIds(Arrays.asList(ids));
        return Result.ok("删除成功");
    }

    @PostMapping("/add")
    public Result add(@RequestBody User user) {
        userService.save(user);
        return Result.ok("添加成功");
    }

    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        User user = userService.getById(id);
        return Result.ok(user);
    }

    @PutMapping("/update")
    public Result update(@RequestBody User user) {
        userService.saveOrUpdate(user);
        return Result.ok("更新成功");
    }

    @PostMapping("/login")
    public Result login(@RequestBody UserLogin userLogin, HttpServletRequest request) {
        //先判断验证码是否正确
        String captcha = (String) redisTemplate.opsForValue().get(CommonUtil.getCaptchaKey(request));
        if (StringUtils.isEmpty(captcha)) {
            return Result.error("验证码已失效");
        }
        if (!captcha.equalsIgnoreCase(userLogin.getCaptcha())) {
            return Result.error("验证码错误");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", userLogin.getName());
        //根据用户名查询
        User loginUser = userService.getOne(queryWrapper);
        //判断用户名是否存在
        if (loginUser == null) {
            return Result.error("用户名错误");
        }
        //判断密码是否正确
        if (!userLogin.getPassword().equalsIgnoreCase(loginUser.getPassword())) {
            return Result.error("密码错误");
        }

        //登录成功
        Map<String, Object> map = new HashMap<>();
        map.put("id", loginUser.getId());
        map.put("name", loginUser.getName());
        String token = JwtUtil.createToken(map);
        return Result.ok("登录成功", token);
    }

    @GetMapping("/userInfo")
    public Result userInfo(@RequestHeader(name = "Authorization") String token) {
        Map<String, Object> map = JwtUtil.parseToken(token);
        String name = (String) map.get("name");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        User user = userService.getOne(queryWrapper);
        return Result.ok(user);
    }

    @PutMapping("/updateStatus/{id}/{status}")
    public Result updateStatus(@PathVariable Integer id, @PathVariable Integer status) {
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id).set("status", status);
        userService.update(updateWrapper);
        return Result.ok("更新成功");
    }
}
